package com.music.note_android.ui.search

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.music.note_android.R
import com.music.note_android.databinding.ItemSearchSuggestionBinding

class SearchSuggestionAdapter(
    private val onSuggestionClick: (String) -> Unit,
    private val onSuggestionDelete: (String) -> Unit
) : ListAdapter<SearchSuggestion, SearchSuggestionAdapter.SuggestionViewHolder>(SuggestionDiffCallback()) {
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SuggestionViewHolder {
        val binding = ItemSearchSuggestionBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return SuggestionViewHolder(binding)
    }
    
    override fun onBindViewHolder(holder: SuggestionViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
    
    inner class SuggestionViewHolder(private val binding: ItemSearchSuggestionBinding) :
        RecyclerView.ViewHolder(binding.root) {
        
        fun bind(suggestion: SearchSuggestion) {
            binding.apply {
                textSuggestion.text = suggestion.text
                
                // 设置图标
                when (suggestion.type) {
                    SearchSuggestionType.HISTORY -> {
                        imageSuggestionIcon.setImageResource(R.drawable.ic_history)
                        buttonDelete.visibility = android.view.View.VISIBLE
                    }
                    SearchSuggestionType.SUGGESTION -> {
                        imageSuggestionIcon.setImageResource(R.drawable.ic_search)
                        buttonDelete.visibility = android.view.View.GONE
                    }
                }
                
                // 点击事件
                root.setOnClickListener {
                    onSuggestionClick(suggestion.text)
                }
                
                // 删除按钮点击事件
                buttonDelete.setOnClickListener {
                    onSuggestionDelete(suggestion.text)
                }
            }
        }
    }
    
    class SuggestionDiffCallback : DiffUtil.ItemCallback<SearchSuggestion>() {
        override fun areItemsTheSame(oldItem: SearchSuggestion, newItem: SearchSuggestion): Boolean {
            return oldItem.text == newItem.text && oldItem.type == newItem.type
        }
        
        override fun areContentsTheSame(oldItem: SearchSuggestion, newItem: SearchSuggestion): Boolean {
            return oldItem == newItem
        }
    }
}

data class SearchSuggestion(
    val text: String,
    val type: SearchSuggestionType
)

enum class SearchSuggestionType {
    HISTORY,
    SUGGESTION
}